package com.crimerank;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.crimerank.data.Incident;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Incidents extends BaseListActivity {

	private RailIncidentAdapter m_adapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.railincidents);
		
		// Setup the list adapter
		m_adapter = new RailIncidentAdapter(this, R.layout.incidentrow,new ArrayList<Incident>());
		setListAdapter(m_adapter);
		
		// Request the data
		requestData();
	}
	
	private void requestData() {
		try {
			String url = getResources().getString(
					R.string.URL_RAIL_INCIDENTS);
			String query = String.format("api_key=%s",
					URLEncoder.encode("s2f5rag8pa5fz53mg2e7s4et", "UTF-8"));

			// Perform the HTTP request
			String result = doHttpRequest(url, query);

			// Process result and update display
			processJson(result);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public void processJson(String str) throws JSONException {
		m_adapter.clear();

		// Loop thru JSON array and parse out bus stops
		JSONObject jo = new JSONObject(str);
		JSONArray ja = jo.getJSONArray("Incidents");
		for (int i = 0; i < ja.length(); i++) {
			Incident incident = new Incident();
			JSONObject tmp = (JSONObject) ja.get(i);
			
			incident.setDateUpdated(tmp.getString("DateUpdated"));
			incident.setDelaySeverity(tmp.getString("DelaySeverity"));
			incident.setDescription(tmp.getString("Description"));
			incident.setEmergencyText(tmp.getString("EmergencyText"));
			incident.setEndLocationFullName(tmp.getString("EndLocationFullName"));
			incident.setIncidentID(tmp.getString("IncidentID"));
			incident.setIncidentType(tmp.getString("IncidentType"));
			incident.setLinesAffected(tmp.getString("LinesAffected"));
			incident.setPassengerDelay(tmp.getString("PassengerDelay"));
			incident.setStartLocationFullName(tmp.getString("StartLocationFullName"));
			
			// Add incident to list
			m_adapter.add(incident);
		}
		
		if(ja.length() == 0){
			Incident incident = new Incident();
			incident.setDescription("No incidents reported at this time");
			incident.setIncidentID("#none#");
			
			// Add incident to list
			m_adapter.add(incident);
		}
	}
	
	public void onClick(View v) {
		Intent myIntent;
		switch (v.getId()) {
		case (R.id.incidentHome):
			myIntent = new Intent(v.getContext(), Home.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivityForResult(myIntent, 0);
			break;
		case (R.id.incidentRefresh):
			requestData();
			break;
		}
	}
	
	private class RailIncidentAdapter extends ArrayAdapter<Incident> {

		private ArrayList<Incident> items;

		public RailIncidentAdapter(Context context, int textViewResourceId, ArrayList<Incident> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if (view == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = vi.inflate(R.layout.incidentrow, null);
			}

			Incident incident = items.get(position);

			if (incident != null) {
				if(incident.getIncidentID().equals("#none#")){
					LinearLayout temp = (LinearLayout)view.findViewById(R.id.viewDrop);
					temp.removeAllViews();
					
					// Get current time
					Time time = new Time();
					time.setToNow();
					
					// Set last updated
					TextView lastUpdate = (TextView) view.findViewById(R.id.incidentDate);
					lastUpdate.setText("Last Updated: " + time.format("%Y/%m/%d %H:%M:%S"));
					
					// Set description
					TextView desc = (TextView) view.findViewById(R.id.incidentDescription);
					desc.setText(incident.getDescription());
				} else {
					TextView desc = (TextView) view.findViewById(R.id.incidentDescription);
					TextView delay = (TextView) view.findViewById(R.id.incidentPassengerDelay);
					TextView severity = (TextView) view.findViewById(R.id.incidentDelaySeverity);
					TextView affected = (TextView) view.findViewById(R.id.incidentLinesAffected);
					
					if(desc != null && delay != null && severity != null && affected != null){
						desc.setText(incident.getDescription());
						delay.setText("Passanger Delay: " + incident.getPassengerDelay());
						severity.setText("Delay Severity: " + incident.getDelaySeverity());
						affected.setText("Lines Affected: " + incident.getLinesAffected());
					}
					
					// Parse the date
					String strDate = incident.getDateUpdated();
					strDate = strDate.replaceAll("[/Ddate\\(\\)]", "");
					strDate = strDate.replaceAll("\\+\\d\\d\\d\\d", "");
					Date date = null;
					try {
						date = new Date(Long.parseLong(strDate)-1000*60*60*4);
						TextView dateTxt = (TextView) view.findViewById(R.id.incidentDate);
						if(dateTxt != null){
							dateTxt.setText("Last Updated: " + date.toLocaleString());
						}
					} catch (NumberFormatException e) {}
				}
			}

			return view;
		}
	}

}
